<template>
  <div id="app">
    <todo-header></todo-header>
    <todo-input @add="addTodoItem"></todo-input>
    <todo-list :list="todos"></todo-list>
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoInput from './components/TodoInput.vue'
import TodoList from './components/TodoList.vue'

// 全局待办事项 id 编号
let index = 3

export default {
  name: 'App',
  components: { // 局部组件注册
    TodoHeader,
    TodoInput,
    TodoList
  },
  data() {
    return {
      // 定义数组来保存所有待办事项
      todos: [
        {
          id: 1,
          title: '复习 JavaScript',
          completed: true
        },
        {
          id: 2,
          title: '使用 vue 实现待办事项列表',
          completed: false
        }
      ]
    }
  },
  methods: {
    /**
     * 添加新待办事项
     */
    addTodoItem(title) {
      this.todos.push({
        id: index++,
        title,
        completed: false
      })
    },
    /**
     * 切换待办事项状态
     */
    toggleTodoItem(id) {
      this.todos = this.todos.map(todo => {
        const copy = { ...todo }
        if (copy.id === id) {
          copy.completed = !copy.completed
        }
        return copy
      })
    },
    /**
     * 删除待办事项
     */
    removeTodoItem(id) {
      this.todos = this.todos.filter(todo => todo.id !== id)
    }
  },
  // 这是一个生命周期的钩子函数，是在 vue 实例创建后执行
  // 先暂时固定记住
  created() {
    console.log('created...', this.todos)
    // 调用全局 event-bus 对象，注册事件监听，准备接收数据
    this.$bus.$on('toggle', this.toggleTodoItem)
    this.$bus.$on('remove', this.removeTodoItem)
  },
  beforeCreate() {
    console.log('before create...', this.todos)
  },
  beforeMount() {
    console.log('before mount...')
  },
  mounted() {
    console.log('mounted...')
  },
  beforeUpdate() {
    console.log('before update...')
  },
  updated() {
    console.log('updated...')
  },
  beforeDestroy() {
    console.log('before destroy...')
  },
  destroyed() {
    console.log('destroyed...')
  }
}
</script>

<style lang="scss">
</style>
